// 引入 vue 模块
import Vue from 'vue'
// 引入项目根组件
import xtApp from '../app.vue'
// 引入 vuex
import {store} from "@/init/vuex.js"
// vuex 快捷操作方法
import {getState, getGetter, setMutation, setAction} from "@/util/store.js";
// 引入 vue-router
import {router} from "@/init/router.js";
// vue-router 快捷操作方法
import {xtPush, xtReplace, xtGo} from "@/util/router.js";
// 引入 element-ui 组件库
import "@/init/element-ui.js"
// 引入 lodash
import _ from "lodash"

// 值为 false, 在生产模式下, 取消控制台中一些不必要的提示
Vue.config.productionTip = false

// 为 Vue 的原型添加快捷方法
Vue.prototype.xtState = getState
Vue.prototype.xtGetter = getGetter
Vue.prototype.xtMutation = setMutation
Vue.prototype.xtAction = setAction
Vue.prototype.xtPush = xtPush
Vue.prototype.xtReplace = xtReplace
Vue.prototype.xtGo = xtGo
Vue.prototype.lodash = _

// 全局混入
Vue.mixin({
    props: {
        params: {
            type: Object
        }
    },
    data() {
        return {
            param: this.params
        }
    },
    methods: {
        getParam() {
            if (this.param) {
                return this.param
            }
            let param = sessionStorage.getItem(this.getLocalStorageName())
            if (param) {
                this.param = JSON.parse(param)
                return this.param
            }
            this.param = undefined
            return this.param
        },
        getLocalStorageName() {
            if (this.$route?.fullPath) {
                return this.$route.fullPath + '-' + 'param'
            }
            return 'xxx' + '-' + 'param'
        },
        setParamToLocalStorage() {
            let param = this.getParam()
            if (param) {
                sessionStorage.setItem(this.getLocalStorageName(), JSON.stringify(param))
            } else {
                sessionStorage.removeItem(this.getLocalStorageName())
            }
        },
        isCurrentRoute() {
            let componentRouteFullPath = this.$route?.fullPath
            let currentRouteFullPath = this.$router?.currentRoute?.fullPath
            return (componentRouteFullPath === currentRouteFullPath) && componentRouteFullPath && currentRouteFullPath
        }
    },
    mounted() {
        this.getParam()
        if (this.isCurrentRoute()) {
            window.addEventListener('beforeunload', this.setParamToLocalStorage)
        }

    },
    beforeDestroy() {
        if (this.isCurrentRoute()) {
            window.removeEventListener('beforeunload', this.setParamToLocalStorage)
        }
    },
    beforeRouteLeave(to, from, next) {
        if (to.fullPath === from.fullPath) {
            return
        }
        this.setParamToLocalStorage()
        next()
    }
})

// xtApp 对象中包含了 render 渲染函数
new Vue({
    render: h => h(xtApp),
    store,
    router
}).$mount('#app')